package com.gainscha.sdk.demo.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.SeekBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

import com.gainscha.fimage.FImage;
import com.gainscha.sdk.demo.R;
import com.gainscha.sdk.demo.databinding.ActivityBitmapAdjustBinding;

import java.io.IOException;

public class BitmapAdjustActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private ActivityBitmapAdjustBinding binding;
    private static float brightness, gamma;
    private Bitmap originBitmap;
    public static final String EXTRA_BRIGHTNESS = "brightness";
    public static final String EXTRA_GAMMA = "gamma";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBitmapAdjustBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());

        try {
            originBitmap = BitmapFactory.decodeStream(getAssets().open("avatar/1.jpg"));
            binding.image.setImageBitmap(originBitmap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        binding.seekbarBrightness.setOnSeekBarChangeListener(this);
        if(brightness != 0) {
            binding.seekbarBrightness.setProgress((int) ((brightness + 100f) / 2f));
        }else {
            binding.seekbarBrightness.setProgress(50);
        }
        binding.seekbarContrast.setOnSeekBarChangeListener(this);
        if(gamma != 0) {
            binding.seekbarContrast.setProgress((int) (100 * gamma / 5f));
        }else {
            binding.seekbarContrast.setProgress(50);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.seekbar_brightness:
                brightness = progress * 2 - 100f;
                break;
            case R.id.seekbar_contrast:
                gamma = 5f * progress / 100f;
                break;
        }
        Log.i("bitmap", String.format("%.2f %.2f", brightness, gamma));
        Bitmap bitmap = FImage.threshold(originBitmap, brightness, gamma, true);
        binding.image.setImageBitmap(bitmap);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_BRIGHTNESS, brightness);
        intent.putExtra(EXTRA_GAMMA, gamma);
        setResult(RESULT_OK, intent);
    }
}